/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals settings, Dir, Application, DBPlugin, qsTr, MessageBox, Dialog, FileDialog, print, SpinBox, GroupBox, LineEdit, ToolButton, serialization, ProgressDialog, MnUi*/
/*jslint plusplus: true, indent: 4*/

function dbExportDocuments() {
	"use strict";
    var db, dialog, sbFrom, sbTo, gbRange, leDirectory, tbOpenDir, gbFolder, dirname, oldFileHistory,
		progress, count, cid, dw, filename,
		dirSettingsKey = "Database/Export Documents/Last Directory",
		dirName = settings.value(dirSettingsKey, Dir.home());

	// Choose database
    Application.mainWindow.doAction("dbDatabaseOpen");
	if (!(DBPlugin.client.connected() && DBPlugin.client.database.length > 0)) {
		return;
	}

	// Check that we have something to export
	db = DBPlugin.client.definition(DBPlugin.client.database);

    if (db.records <= 0) {
		MessageBox.critical(qsTr("Database '{0}' is empty.".format(db.name)));
		return;
	}

    // Dialog for record range and destination folder
	dialog = new Dialog(qsTr("Export Documents"));
	dialog.onOpenDir = function () {
		var dirName = this.text;
		dirName = FileDialog.getExistingDirectory(dirName);
		print("Directory: " + dirName);
		if (dirName.length > 0) {
			this.text = dirName;
		}
	};

	sbFrom = new SpinBox();
	sbFrom.minimum = 1;
	sbFrom.maximum = db.records;
	sbFrom.value = 1;

	sbTo = new SpinBox();
	sbTo.minimum = 1;
	sbTo.maximum = db.records;
	sbTo.value = sbTo.maximum;

	gbRange = new GroupBox();
	gbRange.title = qsTr("Select Records");
	gbRange.add(qsTr("From:"), sbFrom);
	gbRange.add(qsTr("To:"), sbTo);

	leDirectory = new LineEdit();
	leDirectory.label = qsTr("Base Directory:");
	leDirectory.text = dirName;

	tbOpenDir = new ToolButton();
	tbOpenDir.text = "...";
	tbOpenDir.clicked.connect(leDirectory, dialog.onOpenDir);

	gbFolder = new GroupBox();
	gbFolder.title = qsTr("Export to:");
	gbFolder.add(leDirectory, tbOpenDir);

	dialog.add(gbRange);
	dialog.add(gbFolder);

	if (!dialog.exec()) {
		return;
	}

// Save settings
	dirname = leDirectory.text;
	settings.setValue(dirSettingsKey, dirname);

// Export
	oldFileHistory = serialization.fileHistory;
	serialization.fileHistory = false;

	progress = new ProgressDialog();
	progress.setRange(sbFrom.value, sbTo.value + 1);
	progress.show();

	count = 0;
    for (cid = sbFrom.value; cid <= sbTo.value && !progress.wasCanceled; ++cid) {
		progress.value = cid;
		progress.labelText = qsTr("Exporting record {0} ({1} of {2})...").format(cid, cid - sbFrom.value + 1, sbTo.value - sbFrom.value + 1);
		Application.mainWindow.processEvents();

// Retrieve record and paste into new document
		dw = Application.mainWindow.newDocument();
		print("Retrieving record " + cid + "...");
		DBPlugin.getRecord(DBPlugin.client, cid);
		print("Pasted " + dw.itemCount() + " items from record id " + cid + ".");
		if (dw.itemCount() > 0) {
			// Save document
			filename = dirname + "/" + db.name + "-" + cid + ".mnova";
			print("Saving " + filename);
			serialization.save(filename, "mnova");
			count++;
		} else {
			MessageBox.warning(qsTr("Could not find object data for record {0} in database {1}.").replace('{0}', cid).replace('{1}', DBPlugin.client.database));
		}
		dw.close();
	}
    progress.close();
	print("All done");
	serialization.fileHistory = oldFileHistory;
	MessageBox.information(qsTr("Exported {0} documents to {1}.").format(count, dirname));
}

if (this.MnUi && MnUi.scripts_db) {
	MnUi.scripts_db.scripts_db_ExportDocuments = dbExportDocuments;
}
